package fr.xebia.monitoring.config;

import java.util.List;

public class MonitorConfigManager {

	protected MonitorLevel root;

	public void configure(MonitoringConfig monitoringConfig) {
		Boolean rootEnable = monitoringConfig.getRoot().isEnable();
		this.root = new MonitorLevel("/");
		this.root.setEnable(rootEnable);
		List<MonitorConfig> monitors = monitoringConfig.getMonitor();
		for (MonitorConfig monitorConfig : monitors) {
			String categoryName = monitorConfig.getCategoryName();
			boolean isEnable = monitorConfig.isEnable();
			enableOrDisableMonitor(categoryName, isEnable);
		}
	}

	public void enableOrDisableMonitor(String categoryName, boolean isEnable) {
		MonitorLevel parentLevel = root;
		String[] categorySplitted = categoryName.split("\\.");
		MonitorLevel currentLevel = null;
		for (int i = 0; i < categorySplitted.length; i++) {
			String subCategory = categorySplitted[i];
			if (parentLevel.hasChild(subCategory)) {
				currentLevel = parentLevel.getChild(subCategory);
			}
			else {
				currentLevel = new MonitorLevel(subCategory);
				currentLevel.setParent(parentLevel);
				parentLevel.addChild(currentLevel);
			}
			parentLevel = currentLevel;
		}
		currentLevel.setEnable(isEnable);
	}

	public boolean isCategoryEnabled(String categoryName) {
		MonitorLevel currentLevel = root;
		String[] categorySplitted = categoryName.split("\\.");
		for (int i = 0; i < categorySplitted.length; i++) {
			String subCategory = categorySplitted[i];
			if (currentLevel.hasChild(subCategory) == false) {
				return currentLevel.isEnable();
			}
			currentLevel = currentLevel.getChild(subCategory);
		}
		return currentLevel.isEnable();
	}
}
